<template>
  <view>
    <video id="video" class="w-full h-469" :src="chapter?.video" :title="chapter?.chapter_name" autoplay
      @timeupdate="onVideoTimeUpdate" @seeked="onVideoSeeked" @ended="onVideoEnded" :initial-time="Number(chapter?.last_progress)" />
    <view class="pb-4">
      <view class="px-4 py-3 c-#333 text-40">{{ chapter?.chapter_name || '' }}</view>
      <view class="px-4 relative">
        <view class="poup-content relative">
          <scroll-view class="whitespace-nowrap pb-10 u-border-top u-border-bottom" scroll-x enhanced
            :show-scrollbar="false" :scroll-into-view="`scroll-${chapter?.id}`">
            <view v-for="(item, index) in state.data?.chapter" 
              :key="item.id"
              :id="`scroll-${item.id}`"
              class="course-style"
              :class="[{ 'course-style_selected': chapter?.id == item.id }]" 
              @click="onChapterChange(index)">
              <view class="relative h-160 rounded-1.5 overflow-hidden">
                <image class="absolute left-0 top-0 w-full h-full" :src="item.cover_image" />
                <view class="chapter-mask-wrap">
                  <image class="w-44 h-44" src="/package_square/static/images/ic_play.png" />
                  <view class="absolute right-8 bottom-6 text-20 text-white">{{ item.duration }}</view>
                </view>
              </view>
              <view class="pt-3 px-2 text-maxline-2 text-28">{{ item.chapter_name || '' }}</view>
            </view>
          </scroll-view>
          <view class="catalog-wrap" @click="onToggleCatalogShown(true)">
            <view class="w-28 pb-1 text-28 c-primary">目录</view>
            <u-icon name="play-right-fill" color="#F4AF22" size="28" />
          </view>
        </view>
        <!-- 课程详情 -->
        <view class="py-3 u-border-bottom">
          <view class="mt-3 c-#333 text-40 mt-3 c-#333 text-40 font-semibold">课程详情</view>
          <view class="flex py-3" @click="navigateBack">
            <view class="relative">
              <view v-if="state.data?.class_status == 1" class="label-style label-style2">已购买</view>
              <view v-else class="label-style">会员免费</view>
              <u-image :src="state.data?.cover_image" width="240" height="160" border-radius="12" />
            </view>
            <view class="flex flex-col justify-between ml-2">
              <view class="c-#333 text-28 text-maxline-2">{{ state.data?.class_name || '' }}</view>
              <view class="flex flex-col">
                <view class="c-#b5b5b5 text-24 text-maxline-1">{{ state.data?.desc || '' }}</view>
                <view class="flex mt-1">
                  <u-image :src="state.data?.teacher_image" width="32" height="32" border-radius="50%" />
                  <view class="ml-1 c-#999 text-26">{{ state.data?.teacher_name || '' }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="flex py-3 u-border-bottom">
          <view class="mr-10">
            <view class="c-#666 text-24">课时</view>
            <view class="mt-1 c-#333 text-32 font-semibold">{{ state.data?.chapters_num || 0 }}</view>
          </view>
          <view class="mr-10">
            <view class="c-#666 text-24">在学人数</view>
            <view class="mt-1 c-#333 text-32 font-semibold">{{ state.data?.study_num || 0 }}</view>
          </view>
          <view class="mr-10">
            <view class="c-#666 text-24">总时长</view>
            <view class="mt-1 c-#333 text-32 font-semibold">{{ state.data?.total_duration || '--' }}</view>
          </view>
        </view>
        <view class="py-3">
          <u-image :src="state.data?.teacher_desc" width="686" height="180" border-radius="12" />
        </view>
        <view class="catalog-pop" :style="{ top: state.poupTop + 25 + 'px' }" :class="[{ 'catalog-pop_show': state.showCatalog }]">
          <view class="flex justify-between item-center py-3" @click="onToggleCatalogShown(false)" >
            <view class="text-32 c-#333 font-semibold">目录({{ state.data?.chapter?.length || 0 }})</view>
            <image class="w-44 h-44" src="/package_square/static/images/ic_catalog_close.png" />
          </view>
          <view v-if="state.showCatalogContent" :style="{ height: `calc(100vh - ${state.poupTop}px - 51px)` }" class="catalog-pop_content pb-10">
            <view class="catalog-pop_item_wrap">
              <view v-for="(item, index) in state.data?.chapter" :key="index"
                class="catalog-pop_item flex items-center h-110 p-2.5 bg-white rounded-1" @click="onChapterChange(index)">
                <image v-if="state.chapterIndex == index" class="flex-shrink-0 w-22 h-24 mr-2"
                  src="/package_square/static/images/ic_course_video_playing.png" />
                <view class="flex-1 text-24 text-maxline-2 max-h-70" :class="[state.chapterIndex == index ? 'c-primary' : 'c-#333']">
                  {{ item.chapter_name || '' }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { showModal, navigateBack } from '@/common/util/uni'
import { getOnlineCourseDetail, postOnlineCourseSaveProgress } from '@/common/http/module/square';

const videoCtx = ref()
const state = reactive({
  poupTop: 0,
  poupHeight: 0, 
  id: '',
  fromType: '',
  data: '',
  chapterId: '',
  chapterIndex: 0,
  progress: 0,
  currentTime: 0,
  showCatalog: false,
  showCatalogContent: false,
});

const chapter = computed(() => state.data?.chapter?.length > 0 ? state.data?.chapter[state.chapterIndex] : '')

function loadData() {
  getOnlineCourseDetail(state.id).then((res) => {
    const data = res.data
    state.data = data;

    const index = data?.chapter?.findIndex(item => item.id == state.chapterId)
    state.chapterIndex = index < 0 ? 0 : index
  });
}

async function onChapterChange(index) {
  if (state.chapterIndex == index) return
  videoCtx.value?.stop()
  state.progress = 0
  await saveProgress()
  state.chapterIndex = index
  videoCtx.value?.play()
}

function onVideoTimeUpdate(e) {
  const { currentTime, duration } = e.detail
  state.progress = (currentTime / duration) * 100
  state.currentTime = currentTime
}

async function onVideoEnded() {
  state.progress = 100
  await saveProgress()

  const isAllFinished = state.data.chapter.filter(item => item.progress < 100)?.length == 0
  console.log('onVideoEnded', isAllFinished, state.data.chapter,);
  if (isAllFinished) {
    showModal({
      content: '恭喜您，已经看完当前课程的所有章节，在提升自己的路上又迈出了一大步。\r\n 您可以进行一次【学习心得】的总结哦，让结构化的知识体系深刻印在您的大脑深处。',
      cancelText: '知道了',
      confirmText: '去总结',
      success: ({ confirm }) => {
        if (!confirm) return
        uni.redirectTo({
          url: `/package_square/pages/course/summary/index?fromType=${state.fromType}&id=${state.id}`
        })
      }
    })
  } else if (state.chapterIndex < state.data?.chapter?.length - 1) {
    state.progress = 0
    state.chapterIndex++
  }
}

function saveProgress() {
  const params = {
    class_id: state.id,
    chapter_id: chapter.value?.id,
    progress: state.progress,
    last_progress: state.currentTime
  }

  chapter.value.progress = state.progress
  return postOnlineCourseSaveProgress(params)
}

function onToggleCatalogShown(show) {
  if (show) {
    state.showCatalogContent = true
    state.showCatalog = true
  } else {
    state.showCatalog = false
    setTimeout(() => {
      state.showCatalogContent = false
    }, 300);
  }
}

function loadContentHeight () {
  uni.createSelectorQuery().select('.poup-content').boundingClientRect(data => {
    state.poupTop = data.top
    state.poupHeight = data.bottom
  }).exec();
}

onMounted(() => videoCtx.value = uni.createVideoContext('video'))

onLoad((options) => {
  state.id = options.id;
  state.chapterId = options.chapterId;
  state.fromType = options.fromType;
  loadData();
  loadContentHeight()
});

onUnload(() => {
  videoCtx.value?.stop()
  saveProgress()
})
</script>

<style lang="scss" scoped>
.chapter-mask-wrap {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
}

.course-style {
  display: inline-flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 240rpx;
  height: 280rpx;
  background-color: #f6f6f6;
  color: #333333;
  border-radius: 12rpx;
  margin-right: 20rpx;
  white-space: normal;

  &_selected {
    color: #F4AF22;
  }
}

.label-style {
  position: absolute;
  z-index: 90;
  color: #fff;
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx 0px 12rpx 0rpx;
  background-color: #f4af22;

  &2 {
    background-color: #6FC9E7;
  }
}

.catalog-wrap {
  position: absolute;
  top: 80rpx;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 90rpx;
  height: 146rpx;
  border-radius: 12rpx;
  background-color: #FFFFFF;
  box-shadow: 0rpx 3rpx 6rpx 0rpx rgba(0, 0, 0, 0.16);
}

.catalog-pop {
  // position: absolute;
  position: fixed;
  // top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  // height: fit-content;
  background-color: #f8f8f8;
  padding: 0 32rpx 32rpx 32rpx;
  z-index: 99;
  visibility: hidden;
  transition: all 0.3s ease;
  transform: translateY(100%);

  &_content {
    // height: 600rpx;
    overflow-y: scroll;

    .catalog-pop_item_wrap {
      display: flex;
      flex-wrap: wrap;
    }
    .catalog-pop_item {
      width: calc((100% - 26rpx) / 2);
      margin-right: 26rpx;
      margin-bottom: 20rpx;
    }
    .catalog-pop_item:nth-child(2n) {
      margin-right: 0;
    }
  }

  &_show {
    visibility: visible;
    transition: all 0.3s ease;
    transform: translateY(0%) !important;
  }
}
</style>